package com.example.rwq_test.anno.customAnno.scheduleLock;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Description
 * @Author renweiqiang
 * @Date 2024/5/24 上午11:25
 */
@Slf4j
@Aspect
@Component
public class ScheduleLockAspect {
//    //todo 防止报错，暂时先注掉
//    @Autowired
//    private RedissonClient redissonClient;
//
//    @Pointcut("@annotation(com.example.rwq_test.anno.customAnno.scheduleLock.ScheduleLock)")
//    public void scheduleLock() {
//    }
//
//    @Around("scheduleLock()")
//    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        Method method = signature.getMethod();
//        ScheduleLock annotation = method.getAnnotation(ScheduleLock.class);
//        Object res = null;
//        RLock rLock = null;
//        try {
//            rLock = redissonClient.getLock(annotation.key());
//            boolean locked = rLock.tryLock(annotation.waitTime(), annotation.leaseTime(), annotation.timeUnit());
//            if (locked) {
//                res = joinPoint.proceed();
//            } else {
//                log.info("get schedule lock fail, key:{}", annotation.key());
//            }
//        } catch (Exception e){
//            log.error("get schedule lock error, key:{}", annotation.key(), e);
//        } finally {
//            if (null != rLock && rLock.isHeldByCurrentThread()) {
//                rLock.unlock();
//            }
//        }
//        return res;
//
//    }
}
